<!-- 成控-工厂生产模块-冲裁外发作业：蹇泽阳 -->
<template>
  <div class="app-container">
    <Find :OriginalFilter="{ static: true }" :formList="formList" @findClicked="findClicked" />
    <Find :formList="formList2" @findClicked="findClicked2" :searchImg="false" @filterMethod="filterMethod" />

    <div class="flex mt10" style="width: 100%; background-color: white">
      <el-card shadow="never" :body-style="{ padding: '5px 10px 5px' }">
        <div class="flex">
          <h1 class="f16">外发明细</h1>
        </div>
        <Table
          :tableHeader="tableHeader"
          :tableData="tableData"
          class="mt10"
          @currentRow="currentRow"
          selection
          @selectList="selectTableList"
          :isLoading="isLoading"
        />
      </el-card>
      <el-card shadow="never" :body-style="{ padding: '11px 20px' }">
        <h1 class="f16">外发号码明细</h1>
        <Table :tableHeader="tableHeader2" :tableData="tableData2" />
      </el-card>
    </div>
    <el-card shadow="never" :body-style="{ padding: '5px' }">
      <PageModule :PageData="{ total, buttonS: true }" @pageSizeChange="handleSizeChange" @pageChange="handleCurrentChange" />
    </el-card>

    <!-- 选择部位工艺 -->
    <el-drawer v-model="drawer" :direction="'ttb'" size="small" :with-header="false">
      <span @click="drawer = false" style="float: right; cursor: pointer; color: rgb(7, 7, 7)">X</span>
      <div class="flex AIC" style="flex-direction: column">
        <Find :OriginalFilter="{ static: true }" :searchImg="false" :formList="formList3" @findClicked="findClicked3" />
        <div class="flex mt10 JCC" style="width: 100%; background-color: white">
          <el-card shadow="never" :body-style="{ padding: '5px 10px 5px' }">
            <h1 class="f16">选择外发指令</h1>
            <Table
              :tableHeader="tableHeader3"
              :tableData="tableData3"
              selection
              class="mt10"
              :outTableHeight="150"
              @confirmChange="confirmChange4"
              :tableClass="true"
              :isLoading="isLoading3"
              @selectList="selectTableList2"
              :rowKey="'partName'"
            />
            <img :src="src" alt="" style="width: 300px; height: 150px" />
          </el-card>
        </div>
      </div>
    </el-drawer>
    <!-- 外发项目建档 -->
    <el-drawer v-model="drawer2" :direction="'ttb'" size="small" :with-header="false">
      <span @click="drawer2 = false" style="float: right; cursor: pointer; color: rgb(7, 7, 7)">X</span>
      <div class="flex AIC" style="flex-direction: column">
        <Find :OriginalFilter="{ static: true }" :searchImg="false" :formList="formList4" @findClicked="findClicked4" />
        <div class="flex mt10 JCC" style="width: 100%; background-color: white">
          <el-card shadow="never" :body-style="{ padding: '5px 10px 5px' }">
            <div class="flex">
              <h1 class="f16">外加工项目明细</h1>
              <JDialog
                :tableHeader="tableHeader5"
                :tableData="tableData5"
                :width="72"
                @removeOne="removeOne2"
                :currentTableRow="currentTable5Row"
                :unAdd="true"
                :unEdit="true"
              />
            </div>
            <Table
              :tableHeader="tableHeader5"
              :tableData="tableData5"
              class="mt10"
              :outTableHeight="350"
              @selectList="selectTableList2"
              @currentRow="currentRow3"
              @checkboxChange="checkboxChange5"
            />
          </el-card>
        </div>
      </div>
    </el-drawer>
  </div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import { TableList, selectList, selectSomeList } from '@/plugins/mixin'
import SynchronizationLoginWork from '@/utils/SynchronizationLoginWork'
import fileRequest from '@/utils/fileRequest'
import JMessage from '@/utils/JMessage'
export default defineComponent({
  name: 'BlankingOutwork'
})
</script>
<script lang="ts" setup>
import { i18n, Jzhcn } from '@/i18n'
import { ElMessage, ElTable } from 'element-plus'
import Synchronization from '@/utils/Synchronization'
import { debounce } from 'lodash'
import { computed, onMounted, watch } from 'vue'
import { ref } from 'vue'
const currentTime = computed((item: any) => {
  const now = new Date()
  const year = now.getFullYear()
  const month = now.getMonth() + 1 // 月份从0开始，需要加1
  const day = now.getDate()
  return `${year}-${month}-${day}`
})
const drawer = ref(false)
const drawer2 = ref(false)
const src = ref('')
const unEdit = ref(false)
const formList = ref([
  {
    type: 'input',
    inputPlaceholder: '请输入指令',
    inputValue: ''
  },
  {
    type: 'input',
    inputPlaceholder: '请输入冲刀号',
    inputValue: ''
  },
  {
    type: 'input',
    inputPlaceholder: '请输入型体',
    inputValue: ''
  },
  {
    type: 'input',
    inputPlaceholder: '请输入厂商',
    inputValue: ''
  },
  {
    type: 'input',
    inputPlaceholder: '请输入外发单号',
    inputValue: ''
  },
  {
    type: 'date',
    dateLabel: '外发日期',
    dateValue: ''
  },
  {
    type: 'checkbox',
    checkboxLabel: '未外发',
    checked: true
  },
  {
    type: 'checkbox',
    checkboxLabel: '已外发',
    checked: true
  },
  {
    type: 'button',
    checkboxLabel: '置空',
    bgColor: '#1890FF'
  }
])
const formList2 = ref([
  {
    type: 'select',
    selectP: '选择指令',
    selectLabel: '选择外发项目',
    selectValue: '',
    selectOptions: []
  },
  {
    type: 'button',
    checkboxLabel: '选择部位工艺'
  },
  {
    type: 'dateSingle',
    dateLabel: '交期',
    dateValue: currentTime.value
  },
  {
    type: 'button',
    checkboxLabel: '形成外发加工单'
  },
  {
    type: 'button',
    checkboxLabel: '导出合同'
  },
  {
    type: 'button',
    checkboxLabel: '整个加工单删除'
  },
  {
    type: 'button',
    checkboxLabel: '导出明细'
  },
  {
    type: 'button',
    checkboxLabel: '外发项目建档'
  }
]) as any
const formList3 = ref([
  {
    type: 'button',
    checkboxLabel: '生成外发资料'
  }
])
const formList4 = ref([
  {
    type: 'input',
    inputPlaceholder: '请输入序号',
    inputValue: ''
  },
  {
    type: 'input',
    inputPlaceholder: '请输入外加工项目',
    inputValue: ''
  },
  {
    type: 'button',
    checkboxLabel: '插入'
  }
])
const tableHeader = ref([
  {
    change: true,
    label: '生产日期',
    prop: 'purDate'
  },
  {
    change: true,
    label: '指令号',
    prop: 'lotNo'
  },
  {
    change: true,
    label: '型体',
    prop: 'style',
    width: '120px'
  },
  {
    change: true,
    label: '颜色',
    prop: 'color',
    width: '120px'
  },
  {
    change: true,
    label: '工艺',
    prop: 'process'
  },
  {
    change: true,
    label: '部位名称',
    prop: 'partName',
    width: '120px'
  },
  {
    change: true,
    label: '片数',
    prop: 'cutNum'
  },
  {
    change: true,
    label: '订单数量',
    prop: 'orderQty'
  },
  {
    change: true,
    label: '外发数量',
    prop: 'purQty'
  },
  {
    change: true,
    label: '外发单号',
    prop: 'slipNo',
    width: '120px'
  },
  {
    change: true,
    label: '厂商',
    prop: 'vendor',
    width: '125px'
  },
  {
    change: true,
    type: 'dateSingle2',
    label: '交期',
    prop: 'deliveryDate',
    width: '120px'
  },
  {
    type: 'number',
    precision: 6,
    label: '单价',
    prop: 'price',
    width: '50px'
  },
  {
    change: true,
    label: '金额',
    prop: 'amt'
  },
  {
    change: true,
    label: '检核',
    prop: 'cfmFlag'
  },
  {
    change: true,
    label: '扣除预补',
    prop: 'subSurplusFlag'
  },
  {
    label: '备注',
    prop: 'purMemo'
  }
])
const tableHeader2 = ref([
  {
    label: '号码',
    prop: 'sizeNo'
  },
  {
    label: '冲刀号码',
    prop: 'cutSize'
  },
  {
    label: '双数',
    prop: 'qty'
  }
])
const tableHeader3 = ref([
  {
    change: true,
    width: '250px',
    label: '指令/工序部位/号码/轮次',
    prop: 'partName'
  },
  {
    change: true,
    label: '可外发数量',
    prop: 'outQty'
  },
  {
    label: '实际外发数量',
    prop: 'thisQty'
  }
])
const tableHeader4 = ref([
  {
    change: true,
    label: '号码',
    prop: 'seqNo'
  },
  {
    change: true,
    label: '冲刀号码',
    prop: 'cutSize'
  },
  {
    change: true,
    label: '订单数',
    prop: 'orderQty'
  },
  {
    change: true,
    label: '成型预补',
    prop: 'surplusQty'
  },
  {
    change: true,
    label: '可外发量',
    prop: 'outQty'
  },
  {
    label: '本次外发数量',
    prop: 'thisQty'
  }
])
const tableHeader5 = ref([
  {
    change: true,
    label: '序号',
    prop: 'partSeq'
  },
  {
    change: true,
    label: '外加工项目',
    prop: 'partName'
  },
  {
    type: 'checkbox',
    label: '需要预补',
    prop: 'sSurplusFlag'
  }
])
// 表一模块
const findClicked = (content: string) => {
  if (content === '置空') {
    formList.value.forEach((item: any) => {
      item.inputValue = ''
      item.selectValue = ''
      item.dateValue = ''
    })
  }
}
const findClicked2 = async (content: string) => {
  if (content === '选择部位工艺') {
    const lotNo = formList2.value[0].selectValue
    if (lotNo === '') {
      ElMessage('请输入指令')
      return
    } else {
      tableData4.value = []
      getTable3List()
    }
  }
  if (content === '形成外发加工单') {
    const deliveryDate =
      formList2.value.find((item: any) => item.dateLabel && Jzhcn.Find[item.dateLabel.split('.')[1] as keyof typeof Jzhcn.Find] === '交期')
        ?.dateValue + ' 00:00:00'
    if (selectedLists.value.length === 0) {
      JMessage.warning('请打勾外发项目')
      return
    }
    if (selectedLists.value.some((item: any) => item.cfmFlag === '已检验')) {
      JMessage.warning('已检验不能形成外发单号')
      return
    }
    const res = (await SynchronizationLoginWork.post('/Outgoing/getFormAnExternalProcessingOrder', {
      deliveryDate,
      ids: selectedLists.value.map((item: any) => item.id),
      numberList: selectedLists.value.map((item: any) => {
        return {
          lotNo: item.lotNo,
          style: item.style,
          partName: item.partName,
          reqNo: item.reqNo
        }
      })
    })) as any
    if (res.code === 200) {
      JMessage.success(res.message)
      getTableList()
    } else {
      JMessage.error(res.message)
    }
  }
  if (content === '整个加工单删除') {
    const res = (await SynchronizationLoginWork.get(`/Outgoing/DeleteTheEntireAdditionalOrder?slipNo=${currentTableRow.value.slipNo}`)) as any
    if (res.code === 200) {
      JMessage.success('整个加工单删除成功')
      getTableList()
    } else {
      JMessage.error(res.message)
    }
  }
  if (content === '外发项目建档') {
    drawer2.value = true
    formList4.value.forEach((item: any) => {
      item.inputValue = ''
    })
    getTable5List()
  }
  if (content === '导出合同') {
    const res = (await fileRequest.get(`/Outgoing/ExportContract?slipNo=${currentTableRow.value.slipNo}`)) as any
    const link = document.createElement('a') // 利用a标签自定义下载文件名
    let blob = new Blob([res.data]) // 创建Blob对象，设置文件类型
    link.style.display = 'none'
    //设置连接
    link.href = window.URL.createObjectURL(blob)
    const FileName = decodeURI(res.headers['content-disposition'].split(`filename=`)[1])
    link.download = FileName //自定义文件名字
    document.body.appendChild(link)
    //模拟点击事件
    link.click()
    document.body.removeChild(link)
  }
  if (content === '导出明细') {
    const res = (await fileRequest.post(`/Outgoing/ExportDetails`, {
      lotNo: formList.value.find(
        (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '请输入指令'
      )?.inputValue,
      purDateEnd: formList.value.find(
        (item: any) => item.dateLabel && Jzhcn.Find[item.dateLabel.split('.')[1] as keyof typeof Jzhcn.Find] === '外发日期'
      )?.dateValue?.[1],
      purDateStart: formList.value.find(
        (item: any) => item.dateLabel && Jzhcn.Find[item.dateLabel.split('.')[1] as keyof typeof Jzhcn.Find] === '外发日期'
      )?.dateValue?.[0],
      slipNo: formList.value.find(
        (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '请输入外发单号'
      )?.inputValue,
      style: formList.value.find(
        (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '请输入型体'
      )?.inputValue,
      vendor: formList.value.find(
        (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '请输入厂商'
      )?.inputValue,
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      status: cfmFlag(), //	有无欠数(Y/N)	string	body	true
      outDispatchType: 0
    })) as any
    const link = document.createElement('a') // 利用a标签自定义下载文件名
    let blob = new Blob([res.data]) // 创建Blob对象，设置文件类型
    link.style.display = 'none'
    //设置连接
    link.href = window.URL.createObjectURL(blob)
    const FileName = decodeURI(res.headers['content-disposition'].split(`filename=`)[1])
    link.download = FileName //自定义文件名字
    document.body.appendChild(link)
    //模拟点击事件
    link.click()
    document.body.removeChild(link)
  }
}
const findClicked3 = async (content: string) => {
  if (content === '生成外发资料') {
    let arr = [] as any
    const outList = JSON.parse(JSON.stringify(selectedLists2.value))
      .map((item: any, index: any) => {
        if (item.children) {
          arr = item
        } else {
          arr.numberList.push(selectedLists2.value[index])
        }
        return item
      })
      .filter((item: any) => item.children)
    outList.forEach((item: any, index: any) => {
      if (item.numberList) item.totalQty = item.numberList.reduce((total: number, item2: any) => total + Number(item2.thisQty), 0)
    })
    const res = (await SynchronizationLoginWork.post(`/Outgoing/GenerateOutsourcedMaterials/${0}`, {
      outList: outList
    })) as any
    if (res.code === 200) {
      JMessage.success(res.message)
      // outList.value = []
      drawer.value = false
      getTableList()
    } else {
      JMessage.error(res.message)
    }
  }
}
const findClicked4 = async (content: string) => {
  if (content === '插入') {
    const partName = formList4.value.find(
      (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '请输入外加工项目'
    )?.inputValue
    const res = (await SynchronizationLoginWork.post('/Outgoing/getOutsourcedProjectsAdd', {
      partName: partName
    })) as any
    if (res.code === 200) {
      JMessage.success(res.message)
      drawer2.value = false
    } else {
      JMessage.error(res.message)
    }
  }
}
const tableData = ref([])
const tableData2 = ref([])
const tableData3 = ref([]) as any
const tableData4 = ref([]) as any
const tableData5 = ref([])
const isLoading = ref(true)
// 分页器
const currentPage = ref(1)
const pageSize = ref(40)
const total = ref(0)
const handleSizeChange = (val: number) => {
  pageSize.value = val
  getTableList()
}
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  getTableList()
}
// 表格计算函数
const cfmFlag = () => {
  const Unaudited = formList.value.find((item: any) => item.type === 'checkbox' && i18n.global.t(item.checkboxLabel) === '未外发')
  const Audited = formList.value.find((item: any) => item.type === 'checkbox' && i18n.global.t(item.checkboxLabel) === '已外发')
  if (!Unaudited || !Audited) return
  if (Unaudited.checked && Audited.checked) {
    return null
  } else if (Unaudited.checked) {
    return 0
  } else if (Audited.checked) {
    return 1
  } else {
    ElMessage('必须至少选择一项')
    Unaudited.checked = true
    Audited.checked = true
    return null
  }
}
// 获取表数据
const getTableList = debounce(async () => {
  isLoading.value = true
  let tableDataList = await Synchronization.post<any, any>('/Outgoing/getOutsourcedDetailsList', {
    lotNo: formList.value.find(
      (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '请输入指令'
    )?.inputValue,
    purDateEnd: formList.value.find(
      (item: any) => item.dateLabel && Jzhcn.Find[item.dateLabel.split('.')[1] as keyof typeof Jzhcn.Find] === '外发日期'
    )?.dateValue?.[1],
    purDateStart: formList.value.find(
      (item: any) => item.dateLabel && Jzhcn.Find[item.dateLabel.split('.')[1] as keyof typeof Jzhcn.Find] === '外发日期'
    )?.dateValue?.[0],
    slipNo: formList.value.find(
      (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '请输入外发单号'
    )?.inputValue,
    style: formList.value.find(
      (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '请输入型体'
    )?.inputValue,
    vendor: formList.value.find(
      (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '请输入厂商'
    )?.inputValue,
    pageNum: currentPage.value,
    pageSize: pageSize.value,
    status: cfmFlag(), //	有无欠数(Y/N)	string	body	true
    outDispatchType: 0
  })
  isLoading.value = false
  tableData.value = tableDataList.list.map((item: any) => {
    if (item.subSurplusFlag === '1') item.subSurplusFlag = '扣除'
    if (item.subSurplusFlag === '0') item.subSurplusFlag = '-'
    return item
  })
  total.value = tableDataList.total
  currentRow()
}, 500)
onMounted(() => {
  getTableList()
})
watch(
  () =>
    formList.value.map((item: any) => {
      item.selectValue, item.inputValue, item.dateValue, item.checked
    }),
  () => {
    getTableList()
  }
)

// 点击表给另一张表传数据
const currentTableRow = ref({}) as any
const currentRow = async (row: any = tableData.value[0] ? tableData.value[0] : {}) => {
  currentTableRow.value = row
  let table2Data = await SynchronizationLoginWork.post<any, any>(`/Outgoing/getOutsourcedNumberDetailsList`, row)
  tableData2.value = table2Data.data
  if (row.slipNo) {
    tableHeader.value.forEach((item: any) => {
      item.change = true
    })
    unEdit.value = true
  } else {
    tableHeader.value[9].change = false
    tableHeader.value[11].change = false
    unEdit.value = false
  }
}

// 选择部位工艺
const outList = ref([]) as any
const selectedLists2 = ref([])
const selectTableList2 = (selectedList: any) => {
  selectedLists2.value = selectedList
}
const selectedLists = ref([])
const selectTableList = (selectedList: any) => {
  selectedLists.value = selectedList
}
// 是否修改
const confirmChange4 = (row: any) => {
  if (Number(row.thisQty) > Number(row.outQty)) {
    JMessage.warning('本次外发数量不能大于外发数量')
    row.thisQty = row.outQty
    return
  }
  if (Number(row.thisQty) < 0) {
    JMessage.warning('本次外发数量不能小于0')
    return
  }
}
const isLoading3 = ref(false)
// 获取表格数据
const getTable3List = async () => {
  isLoading3.value = true
  drawer.value = true
  const lotNo = formList2.value[0].selectValue
  const res = (await SynchronizationLoginWork.post(`/Outgoing/SelectPartProcess/${0}`, {
    newLotNo: formList2.value[1].selectValue,
    lotNo
  })) as any
  if (res.code === 200) {
    tableData3.value = res.data[lotNo].map((item: any) => {
      item.numberList = []
      item.children = item.sizeList.map((item2: any) => {
        item2.change = 'Y'
        item2.partName = item2.sizeNo
        return item2
      })
      return item
    })
    src.value = res.data.photo
    isLoading3.value = false
  } else {
    drawer.value = false
    JMessage.warning(res.message)
  }
}
const getTable5List = async () => {
  const res = (await SynchronizationLoginWork.post('/Outgoing/getOutsourcedProjectsList')) as any
  tableData5.value = res.data.map((item: any) => {
    item.change = true
    item.sSurplusFlag === 'Y' ? (item.sSurplusFlag = true) : (item.sSurplusFlag = false)
    return item
  })
  currentRow3()
}

// 点击表给另一张表传数据
const currentTable5Row = ref({}) as any
const currentRow3 = async (row: any = tableData5.value[0]) => {
  currentTable5Row.value = row
}
// 下拉框请求数据
const filterMethod = debounce(async (BigVal: any, selectOptions: any, copyOptions: any, item: any) => {
  if (Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '选择指令' && BigVal !== '') {
    const res = (await SynchronizationLoginWork.post('/Outgoing/getChooseOutsourcedProjects', {
      lotNo: BigVal,
      pageNum: '1',
      pageSize: '9999',
      style: ''
    })) as any
    if (res.code === 200) {
      formList2.value[0].selectOptions.splice(0)
      res.data.list.forEach((item2: any) => {
        formList2.value[0].selectOptions.push({
          optionLabel: item2.lotNo,
          optionKey: item2.lotNo,
          optionValue: item2.lotNo
        })
      })
    } else {
      JMessage.error(res.message)
    }
  } else if (BigVal === '') {
    formList2.value[0].selectOptions.splice(0)
  }
}, 500)
// 下拉框请求数据
const getSelectList = async () => {
  // await selectSomeList(formList2, () => Synchronization.get('/back/getVendorCompanyName'))
  formList2.value[0].selectOptions.push({
    optionLabel: ' ',
    optionKey: ' ',
    optionValue: ' '
  })
}
onMounted(() => {
  getSelectList()
})

const removeOne2 = async () => {
  const { partSeq } = currentTable5Row.value
  const res = (await SynchronizationLoginWork.post(`/Outgoing/getOutsourcedProjectsDel/${partSeq}`)) as any
  if (res.code === 200) {
    JMessage.success('删除成功')
    getTable5List()
  } else {
    JMessage.error('删除失败')
  }
}

// 需要预补的checkbox的change事件处理函数，用于更新外派单信息
const checkboxChange5 = async (prop: any, row: any) => {
  let isCheck = 0
  console.log(prop, row)
  const { partSeq, sSurplusFlag } = row
  sSurplusFlag === true ? (isCheck = 1) : (isCheck = 0)
  const res = (await SynchronizationLoginWork.post(`/Outgoing/getOutsourcedProjectsUpdate/${partSeq}?param=${isCheck}`)) as any
  if (res.code === 200) {
    JMessage.success(res.message)
    getTable5List()
  } else {
    JMessage.error(res.message)
  }
}
</script>

<style lang="less" scoped>
:deep(.el-form-item:nth-last-child(7)) {
  .el-select {
    width: 250px;
    height: 28px;
  }
}

.tableClass {
  :deep(.el-table__header) {
    .el-checkbox {
      opacity: 0 !important;
    }
  }
}
</style>
